import { Component, ElementRef, EventEmitter, Input, OnInit, Output, ViewChild } from '@angular/core';
import { FormGroup, FormBuilder, Validators } from '@angular/forms';
import { Router } from '@angular/router';
import { NzMessageService } from 'ng-zorro-antd';
import { QCLOUD_DOMAIN, UPLOAD_DOMAIN } from '../../../constant/config';
import { MyModalHelper } from '@core/my-modal.helper';
import { CacheService } from '@core/routes-services/cache.service';
import { CompanyService } from '@core/routes-services/company.service';
import { ActivityProductService } from '@core/routes-services/activity-product.service';
import { myValidNull } from '@core/util/string-utils';
import { CompanyTypeService } from '@core/routes-services/company-type.service';

@Component({
  selector: 'step1',
  templateUrl: './step1.component.html',
  styles: [`
    :host ::ng-deep .ant-upload-select-picture-card {
      width: 128px;
      height: 128px;
    }

    :host ::ng-deep .ant-upload-select-picture-card i {
      font-size: 32px;
      color: #999;
    }

    :host ::ng-deep .ant-upload-select-picture-card .ant-upload-text {
      margin-top: 8px;
      color: #666;
    }

    :host ::ng-deep .ant-upload .avatar {
      width: 120px;
      height: 120px;
    }
  `],
})
export class Step1Component implements OnInit {
  entity: any = {};
  validateForm: FormGroup;
  isLoading: boolean = false;
  uploadDomain = UPLOAD_DOMAIN;
  qcloudDomain = QCLOUD_DOMAIN;
  headers: any = {};
  componentDirty: boolean = false;
  @ViewChild('content') content: ElementRef;
  @ViewChild('protocolDescription') protocolDescription: ElementRef;

  @Input() title: any;//商品名称
  @Output() titleChange = new EventEmitter();


  allProducts: any [] = [];
  typeOptions: any [] = [];

  constructor(private router: Router,
              private modalHelper: MyModalHelper,
              public companyService: CompanyService,
              public companyTypeService:CompanyTypeService,
              private activityProductService: ActivityProductService,
              private message: NzMessageService,
              private cacheService: CacheService,
              private fb: FormBuilder) {
  }

  ngOnInit() {
    const token: any = this.cacheService.getTokenInfo();
    this.headers = { 'Authorization': token };
    this.initOption();
    this.entity = this.companyService.entity;
    this.initValidateForm();
  }

  callbackTitle() {
    console.log(this.validateForm.controls.title.value);
  }


  initOption() {
    this.isLoading = true;
    this.activityProductService.getAll().then((res) => {
      if (res.status.toString().startsWith('20')) {
        this.allProducts = res.data.activityProductsList;
        console.log(this.allProducts);
      } else {
        this.message.warning(res.message);
      }
      this.isLoading = false;
    }, error => {
      this.message.error(error.message ? error.message : error.error);
      this.isLoading = false;
    });
    this.companyTypeService.getAll().then((res) => {
      if (res.status.toString().startsWith('20')) {
        this.typeOptions = res.data.companyTypeList;
        console.log(this.typeOptions);
      } else {
        this.message.warning(res.message);
      }
      this.isLoading = false;
    }, error => {
      this.message.error(error.message ? error.message : error.error);
      this.isLoading = false;
    });
  }

  initValidateForm() {
    this.entity.fixedQuantity = this.entity.fixedQuantity == 1 ? 1 : 2;
    this.entity.needProtocol = this.entity.needProtocol == 1 ? 1 : 2;
    this.entity.beginTime = this.entity.beginTime ? new Date(this.entity.beginTime) : null;
    this.entity.endTime = this.entity.endTime ? new Date(this.entity.endTime) : null;
    if (typeof this.entity.activityProductArr == 'string') {
      this.entity.activityProductArr = this.entity.activityProductArr ? JSON.parse(this.entity.activityProductArr) : null;
    }
    this.validateForm = this.fb.group({
      title: [this.entity.title, [Validators.required, Validators.maxLength(60)]],
      forwardingTitle: [this.entity.forwardingTitle, [Validators.required, Validators.maxLength(100)]],
      activityProductId: [this.entity.activityProductId, []],
      activityProductArr: [this.entity.activityProductArr, []],
      fixedQuantity: [this.entity.fixedQuantity, [Validators.required]],
      mainImg: [this.entity.mainImg, [Validators.required]],
      mainBanner: [this.entity.mainBanner, [Validators.required]],
      description: [this.entity.description, [Validators.required]],
      remark: [this.entity.remark, [Validators.required, Validators.maxLength(500)]],
      btnText: [this.entity.btnText, [Validators.maxLength(16)]],
      descText: [this.entity.descText, [Validators.maxLength(32)]],
      descPrice: [this.entity.descPrice, [Validators.min(0)]],
      typeId: [this.entity.typeId, [Validators.required]],
      beginTime: [this.entity.beginTime, []],
      endTime: [this.entity.endTime, []],
      needProtocol: [this.entity.needProtocol, [Validators.required]],
      protocolTitle: [this.entity.protocolTitle, [Validators.maxLength(100)]],
      protocolDescription: [this.entity.protocolDescription, []],
    });
    this.content.nativeElement.innerHTML = this.entity.description ? this.entity.description : '点击进行内容编辑';
    this.protocolDescription.nativeElement.innerHTML = this.entity.protocolDescription ? this.entity.protocolDescription : '点击进行内容编辑';
  }


  isShow: boolean = false;

  showEdit() {
    this.isShow = !this.isShow;
    let body = document.body;
    if (this.isShow) {
      body.style.overflow = 'hidden';
      body.style.userSelect = 'none';
    } else {
      body.style.overflow = '';
      body.style.userSelect = '';
    }
  }

  contentCallback(content) {
    this.entity.description = content;
    this.content.nativeElement.innerHTML = this.entity.description;
    this.componentDirty = true;
    this.validateForm.controls.description.setValue(content);
  }

  isShow1: boolean = false;

  showEdit1() {
    this.isShow1 = !this.isShow1;
    let body = document.body;
    if (this.isShow1) {
      body.style.overflow = 'hidden';
      body.style.userSelect = 'none';
    } else {
      body.style.overflow = '';
      body.style.userSelect = '';
    }
  }

  contentCallback1(content) {
    this.entity.protocolDescription = content;
    this.protocolDescription.nativeElement.innerHTML = this.entity.protocolDescription;
    this.componentDirty = true;
    this.validateForm.controls.protocolDescription.setValue(content);
  }

  submitForm() {
    let $this = this;
    if (this.validateForm.invalid) {
      for (const i in this.validateForm.controls) {
        this.validateForm.controls[i].markAsDirty();
        this.validateForm.controls[i].updateValueAndValidity();
      }
    } else {
      // 启用协议 验证 协议标题和协议内容必填提示
      if (this.validateForm.value.needProtocol == 1) {
        if (myValidNull(this.validateForm.value.protocolTitle)) {
          this.message.warning('启用协议时，协议标题不能为空！');
          return;
        }
        if (myValidNull(this.validateForm.value.protocolDescription)) {
          this.message.warning('启用协议时，协议内容不能为空！');
          return;
        }
      }
      if (!this.entity.id || this.entity.id == 0) {
        //新增到最后一步再同一保存
        this.companyService.entity = this.validateForm.value;
        this.title = this.companyService.entity.title;
        this.titleChange.emit(this.title);
        ++this.companyService.step;
      } else {
        //修改
        if (this.validateForm.dirty || this.componentDirty) {
          this.isLoading = true;
          this.companyService.updateEntity(this.entity.id, this.validateForm.value).then((res) => {
            if (res.status.toString().startsWith('20')) {
              this.message.success('保存成功');
              this.entity = res.data;
              this.companyService.entity = res.data;
              this.title = this.companyService.entity.title;
              this.titleChange.emit(this.title);
              ++this.companyService.step;
            } else {
              this.message.warning(res.message);
            }
            this.isLoading = false;
          }, error => {
            this.message.error(error.message ? error.message : error.error);
            this.isLoading = false;
          });
        } else {
          ++this.companyService.step;
        }
      }
    }
  }

  /**
   * 上传图控件 ng-zorro upload
   *
   * @param {any} file
   * @param {any} fileList
   */
  handleChange({ file, fileList }): void {
    const status = file.status;
    if (status !== 'uploading') {
      // console.log(file, fileList);
    }
    if (status === 'done') {
      this.message.success(`${file.name} 上传成功`);
      let findIdx = fileList.findIndex(w => file.lastModified == w.lastModified);
      fileList[findIdx].imgKey = fileList[findIdx].response.data;
      fileList[findIdx].name = fileList[findIdx].response.data;
      fileList[findIdx].url = this.qcloudDomain + fileList[findIdx].response.data;
      this.entity.mainImg = fileList[findIdx].url;
      this.validateForm.controls.mainImg.setValue(this.entity.mainImg);
      this.componentDirty = true;
    } else if (status === 'error') {
      this.message.error(`${file.name} 上传失败`);
    }
  }
  /**
   * 上传图控件 ng-zorro upload
   *
   * @param {any} file
   * @param {any} fileList
   */
  handleChange1({ file, fileList }): void {
    const status = file.status;
    if (status !== 'uploading') {
      // console.log(file, fileList);
    }
    if (status === 'done') {
      this.message.success(`${file.name} 上传成功`);
      let findIdx = fileList.findIndex(w => file.lastModified == w.lastModified);
      fileList[findIdx].imgKey = fileList[findIdx].response.data;
      fileList[findIdx].name = fileList[findIdx].response.data;
      fileList[findIdx].url = this.qcloudDomain + fileList[findIdx].response.data;
      this.entity.mainBanner = fileList[findIdx].url;
      this.validateForm.controls.mainBanner.setValue(this.entity.mainBanner);
      this.componentDirty = true;
    } else if (status === 'error') {
      this.message.error(`${file.name} 上传失败`);
    }
  }

  goBack() {
    this.companyService.reset();
    this.router.navigate(['/company/list']);
  }


  disabledStartDate = (startValue: Date): boolean => {
    if (!startValue || !this.entity.endTime) {
      return false;
    }
    return startValue.getTime() > this.entity.endTime.getTime();
  };

  disabledEndDate = (endValue: Date): boolean => {
    if (!endValue || !this.entity.beginTime) {
      return false;
    }
    return endValue.getTime() <= this.entity.beginTime.getTime();
  };

  onStartChange(date: Date): void {
    this.entity.beginTime = date;
  }

  onEndChange(date: Date): void {
    this.entity.endTime = date;
  }


  endOpen: boolean = false;

  handleStartOpenChange(open: boolean): void {
    if (!open) {
      this.endOpen = true;
    }
  }

  handleEndOpenChange(open: boolean): void {
    this.endOpen = open;
  }
}
